/*
* play
* update: playground动态尺寸
* date: 2015-09-20
*/
define(function(require, exports, module) {
	var $ = require('jquery');
	var base = require('base');
	var com = require('./common');
	var util = require('./util');
	var etpl = util.etpl;
	var tpl = util.tpl;
	var sort = util.sort;
	var getWidgets = util.getWidgets;
	var showWidgets = util.showWidgets;
	var Storage = util.Storage;
	var jrChannel = util.jrChannel;
	var random = util.random;
	var getTag = util.getTag;
	var mainTemp = util.mainTemp;

	var play = function(Widget,userConfig){
		//去滚动条
		$('html').addClass('docStatic');

		var etplEngine = new etpl.Engine(),
			template = Storage.get('template');

		etplEngine.compile(template);
		var Render = etplEngine.getRenderer( 'playTime' );

		var playTime = Render({
			Widget : Widget,
			viewWidth : 10
		});
		var playBoxObj = $.box(playTime,{
			layout:false,
			bg:false,
			width:9999,
			height:9999,
			onshow:function(){
				$('#playTime').on('click','.playTime_close',function(){
					if($('#configPanel .show').size()){
						$('#configPanel .show').removeClass('show');
					}
					$('html').removeClass('docStatic');
					$.box.hide(playBoxObj);
				});
				
				initWidget(Widget,userConfig ? userConfig : {});
			},
			onclose:function(){
				clearWidget();
			}
		});
	};
	var widgetDef = {};
	var initWidget = function(Widget,userConfig){
		var state = 0;
		//生成组件id
		var wid = "wid"+random();
		$.ajax({
			type:'get',
			url:Widget.config+'?'+random(),
			dataType:'json',
			success:function(res){
				widgetDef = res;
				widgetDef.id = wid;
				getWidgetConfig(Widget,userConfig);
			},
			error:function(){
				getWidgetConfig(Widget,userConfig);
			}
		});
		
	};
	//清除widget
	var clearWidget = function(){
		$('#widgetCssNode').remove();
		$('#widgetJsNode').remove();
		
		Storage.remove("widgetConfigBack");
		Storage.remove("HTML");
		Storage.remove("CSS");
		Storage.remove("JS");
	};

	var getWidgetConfig = function(Widget,userConfig){
		Storage.set("widgetConfigBack",widgetDef);
		
		//深拷贝
		var widgetConfig = $.extend(true,{},widgetDef,userConfig);
		
		//组件演示宽度
		if(widgetConfig.showConfig.viewWidth){
			$('#playView').attr('class','center span-'+widgetConfig.showConfig.viewWidth);
		}

		paintWidget(Widget,widgetConfig,true);
	};

	var paintWidget = function(Widget,widgetConfig,withPanel){
		//扩展id
		(function(){
			var id = widgetConfig.id;
			for(var x in widgetConfig){
				if(x!=="id"){
					widgetConfig[x]["id"] = id;
				}
			}
		})();
		
		//get temp
		var getTemp = function(cb){
			$.ajax({
				type:'get',
				url:Widget.temp+'?'+random(),
				dataType:'html',
				success:function(res){
					var etplEngine = new etpl.Engine();
					var render = etplEngine.compile(res);
					var result = render(widgetConfig.showConfig);
					Storage.set('HTML',result);
					$('#playView').html(result);
					typeof(cb)==='function' && cb();
				},
				error:function(){
					console.warn(Widget.widget+'组件模板未加载！');
				}
			});
		};
		
		//get css
		var getCss = function(cb){
			$.ajax({
				type:'get',
				url:Widget.css+'?'+random(),
				dataType:'text',
				success:function(res){
					var etplEngine = new etpl.Engine();
					var render = etplEngine.compile(res);
					var result = render(widgetConfig.cssConfig);
					if(!$('#widgetCssNode').size()){
						$('head').append('<style id="widgetCssNode"></style>');
					}
					Storage.set('CSS',result);
					$('#widgetCssNode').html(result);
					typeof(cb)==='function' && cb();
				},
				error:function(){
					console.warn(Widget.widget+'组件样式未加载！');
				}
			});
		};
		//get script
		var getScript = function(cb){
			$.ajax({
				type:'get',
				url:Widget.script+'?'+random(),
				dataType:'text',
				success:function(res){
					var etplEngine = new etpl.Engine();
					var render = etplEngine.compile(res);
					var result = render(widgetConfig.jsConfig);
					var jsRandom = random();
					if($('#widgetJsNode').size()){
						$('#widgetJsNode').remove();
					}
					var jsNode = '<script id="widgetJsNode">\
							\ndefine("'+ Widget.widget +'-script-'+jsRandom+'", function(require) {\
									\nvar $ = require("jquery"),base = require("base"),com = require("app/common");\n';
					jsNode += result;		
					jsNode += '\n})';
					jsNode += ('\nseajs.use("'+Widget.widget +'-script-'+jsRandom+'")');
					jsNode += '\n</script>';

					setTimeout(function(){
						Storage.set('JS',result);
						$('body').append(jsNode);
						typeof(cb)==='function' && cb();
					},0);
				},
				error:function(){
					console.warn(Widget.widget+'组件js未加载！');
				}
			});
		};
		//获取组件三部分
		if(withPanel){
			getCss(function(){
				getTemp(function(){
					getScript(function(){
						creatPanel(Widget,widgetConfig);
					});
				});
			});
		}else{
			getCss(function(){
				getTemp(function(){
					getScript();
				});
			});
		}
	};
	//创建配置面板
	var creatPanel = function(Widget,widgetConfig){

		if(typeof(widgetConfig)!='object') {
			console.warn('无法创建配置面板！');
			return;
		}
		//console.log(widgetConfig)
		
		var etplEngine = new etpl.Engine();
		var template = Storage.get('template');
		etplEngine.compile(template);
		var render = etplEngine.getRenderer('panel');
		var result = render(widgetConfig);
		//面板事件
		$('#configPanel').html(result)
		.on('click','.playTime_mark ._tag',function(){
			$(this).parents('.playTime_mark').toggleClass('show').siblings().removeClass('show');
		})
		.on('click','.playTime_mark ._clo',function(){
			$(this).parents('.playTime_mark').removeClass('show');
		});
		//面板监听
		$('.panelWrap').on('change','.form-control',function(){
			var key = $(this).data('key'),
				val = $(this).attr('type')=='number' ? +$(this).val() : $(this).val(),
				dataTree = $(this).parents('form').data('item');
			widgetConfig[dataTree][key]['value'] = val;
			//重绘组件
			paintWidget(Widget,widgetConfig);
		}).on('reset','form',function(e){
			e.preventDefault();
			var dataTree = $(this).data('item');
			var widgetConfigBack = Storage.get("widgetConfigBack");
		
			widgetConfig[dataTree] = widgetConfigBack[dataTree];
			//重绘数组
			paintWidget(Widget,widgetConfig);
			//恢复面板
			var controls = $(this).find('.form-control[data-key]');
			for(var key in widgetConfig[dataTree]){
				controls.each(function(i,e){
					if($(e).data('key')==key){
						if($(e).get(0).tagName.indexOf('ELECT') > 0){
							$(e).find('option').each(function(i2,e2){
								if($(e2).text()==widgetConfig[dataTree][key]['value']){
									$(e2).attr('selected','selected');
									return;
								}
							});
						}else{
							$(e).val(widgetConfig[dataTree][key]['value']);
						}
					}
				});
			}
		});
		//生成差异配置
		require('json');
		$('#getConfig').on('submit',function(e){
			e.preventDefault();
			var newConfig = {userConfig:{}};
			var widgetConfigBack = Storage.get("widgetConfigBack");
			//差异代码
			for (var key in widgetConfigBack){
				if(typeof(widgetConfigBack[key])=='object'){
					for(var key2 in widgetConfigBack[key]){
						for(var key3 in widgetConfigBack[key][key2]){
							if(typeof widgetConfig[key][key2][key3]!='object' && (widgetConfigBack[key][key2][key3]!=widgetConfig[key][key2][key3]) ){
								newConfig.userConfig[key] = $.extend({},newConfig.userConfig[key]);
								newConfig.userConfig[key][key2] = $.extend({},newConfig.userConfig[key][key2]);
								newConfig.userConfig[key][key2][key3] = widgetConfig[key][key2][key3]
							}
						}
					}
				}
			}
			newConfig.widget = Widget.widget;
			var configJson = $.toJSON(newConfig).replace(/^\s+/,"");
			$('#configCodeBox').val(configJson);
			//发布事件
			$('body').trigger('getConfig');
		});

		$('#configCodeBox').on('click',function(){
			$(this).select();
		});

		//复制代码
		require('copy');
		var copyResult = function(str){
			//$('#copyResult').text(str);
			$.box.msg(str,{
				delay:1000
			});
		};
		//HTML
		$('#copyHTML').zclip({
			copy: function(){
				return Storage.get("HTML");
			},
			afterCopy: function() {
				copyResult("HTML代码复制成功");
			}
		});
		//CSS
		$('#copyCSS').zclip({
			copy: function(){
				return Storage.get("CSS");
			},
			afterCopy: function() {
				copyResult("CSS代码复制成功");
			}
		});
		//JS
		$('#copyJS').zclip({
			copy: function(){
				return Storage.get("JS");
			},
			afterCopy: function() {
				copyResult("JS代码复制成功");
			}
		});
	};

	module.exports = play;

});